import { balancePay, wxPrepay, queryOrderStatus, getPreOrderMsgFun } from "@src/sp-mall/api/order";
import { getAccount, getAccountPayConfig } from "@src/api/member";
import md5 from '@src/common/md5'
import router from "/router"
// noinspection DuplicatedCode
module.exports = Behavior({
  data: {
    accountInfo: {},
    accountPayRule: {}
  },
  ready: function () {
    this.$pay = this.selectComponent("#pay");
    this.getAccountInfo();
  },
  methods: {
    onShow() {
      // this.fetchData()
      // this.getAccountInfo();
    },
    getAccountInfo() {
      wx.showLoading({
        title: '加载中',
        mask: true
      })
      Promise.all([this.getAccountData(), this.getAccountPayConfigData(), this.fetchData()]).then(() => {
        console.log(this.data.accountInfo, this.data.accountPayRule)
        wx.hideLoading();
        this.$pay.hideLoading();
      })
    },
    fetchData() {
      // console.log(this.data)
      return new Promise((resolve) => {
        if (!this.data.preNo) return resolve()
        getPreOrderMsgFun(this.data.preNo).then(res => {
          console.log('getPreOrderMsgFun',res)
          let goodsPresell = res.data.goodsPresell
          let preOrder = res.data;
          let depositFee = 0
          if (preOrder.items && preOrder.items.length > 0) {
            let skuId = preOrder.items[0].skuId
            if (goodsPresell && goodsPresell.skuDeposit && goodsPresell.skuDeposit[skuId]) {
              depositFee = goodsPresell.skuDeposit[skuId].deposit;
            }
          }
          if (this.data.leaderCollect === false || this.data.leaderCollect === true) {
            // preOrder.groupInfo=this.data.leaderCollect

          }
          this.setData({
            preOrder: preOrder,
            depositFee: depositFee,
            deliveryType: res.data.type,
            deliveryResult: null,
            orderPayInfo: res.data.orderPayInfo,
            goodsPresell: goodsPresell,
            discountInfo: null, pointsDiscount: null,
            goodsItems: preOrder.items,
            groupInfo: preOrder.groupInfo,//订单中拼团信息，比如是否代收
          });
          const that = this
          // wx.hideLoading()
          if (preOrder.groupInfo && !preOrder.groupInfo.isLeader && preOrder.groupInfo.leaderCollect && !preOrder.groupInfo.leaderCollectOptional && preOrder.type !== preOrder.groupInfo.leaderDeliveryType) {
            let addressName;
            if (preOrder.type === 'EXPRESS') addressName = "直邮到家"
            if (preOrder.type === 'LOCAL') addressName = "送货上门"
            if (preOrder.type === 'SELF_PICKUP') addressName = "到店自提"
            wx.showModal({
              title: '温馨提示',
              content: `你参与的拼团购因为团长选择了代收方式，你选择的${addressName}已被重置为与团长一致，点击确认继续下单`,
              cancelText: "返回", //默认是“取消”
              confirmText: "继续下单", //默认是“确定”
              success(res) {
                if (res.confirm) {
                  that.setData({ deliveryType: preOrder.groupInfo.leaderDeliveryType })
                } else if (res.cancel) {
                  router.back()
                }
              }
            })
          }
          if (preOrder.groupInfo && !preOrder.groupInfo.isLeader && preOrder.groupInfo.leaderCollect && preOrder.groupInfo.leaderCollectOptional && preOrder.type !== preOrder.groupInfo.leaderDeliveryType) {
            wx.showModal({
              title: '温馨提示',
              content: `当前订单支持团长代收，请选择你的收货方式`,
              cancelText: "自己收货", //默认是“取消”
              confirmText: "团长代收", //默认是“确定”
              success(res) {
                that.setData({ ['groupInfo.leaderCollectType']: true })
                if (res.confirm) {
                  that.setData({ ['groupInfo.leaderCollectStatus']: 1 })
                } else if (res.cancel) {
                  that.setData({ ['groupInfo.leaderCollectStatus']: 0 })
                }
              }
            })
          }



          if (this.data.preOrder.presell) {
            this.selectComponent("#saleDialog").open()
          }
          if (this.data.address && res.data.type !== 'SELF_PICKUP') {
            this.fetchFreightFee();
          }
          resolve()
          return res;
        })
      })
    },
    getAccountData() {
      return new Promise((resolve) => {
        getAccount().then(res => {
          this.setData({ accountInfo: res.data || {} })
          resolve()
        })
      })
    },

    getAccountPayConfigData() {
      return new Promise((resolve) => {
        getAccountPayConfig().then(res => {
          this.setData({ accountPayRule: res.data || {} })
          resolve()
        })
      })
    },


    toMallPay(options) {
      console.log('toMallPay - options',options)
      return new Promise(((resolve, reject) => {
        const that = this;
        this.setData({ payResolve: resolve, payReject: reject });
        // 0元使用余额支付
        //充值余额 赠送余额 冻结充值余额 冻结赠送余额
        let accountInfo = this.data.accountInfo;
        //可用余额
        let usableBalance = (accountInfo?.balance || 0) + (accountInfo?.giftBalance || 0) - (accountInfo?.lockedBalance || 0) - (accountInfo?.lockedGiftBalance || 0);
        if (options.payFee === 0 && options.payChannels.indexOf("balance") !== -1 && usableBalance === 0) {
          console.log('商户有开通余额，用户无余额，点击支付直接生成订单，支付方式默认“余额支付”')
          this.startBalancePay(options.orderNo, '')
        }else if(options.payFee === 0 && options.payChannels.indexOf("balance") === -1){
          console.log('商户没开通余额，点击支付直接生成订单，不用选择支付方式，支付方式默认“其他”')
          this.startBalancePay(options.orderNo, '','99')
        } else {
          // 不等于0元的支付
          console.log('进入其他方式')
          if (Object.keys(that.data.accountInfo).length === 0 || Object.keys(that.data.accountPayRule).length === 0 && that.data.accountPayRule.useBalanceScope.indexOf(1) != -1) {
            Promise.all([this.getAccountData(), this.getAccountPayConfigData()]).then(() => {
              that.callbackFn(options)
            })
          } else {
            that.callbackFn(options)
          }
        }
      }))
    },
    callbackFn(options) {
      console.log(options, 11111)
      let { orderNo, payFee, hasDiscount, payChannels } = options;
      let accountPayRule = this.data.accountPayRule;
      if (accountPayRule.useBalanceScope.indexOf(1) == -1) {
        payChannels.splice(payChannels.indexOf('balance'), 1)
      }
      //充值余额 赠送余额 冻结充值余额 冻结赠送余额
      let accountInfo = this.data.accountInfo;
      //可用余额
      let usableBalance = (accountInfo?.balance || 0) + (accountInfo?.giftBalance || 0) - (accountInfo?.lockedBalance || 0) - (accountInfo?.lockedGiftBalance || 0);
      // let balance = accountInfo.balance||0,
      //     giftBalance = accountInfo.giftBalance||0;
      let account = { balance: 0, canUseDiscount: false, requirePassword: false }
      // if (accountInfo.hasOwnProperty("balance")) {
      account = {
        // balance: balance + giftBalance,
        balance: usableBalance,
        canUseDiscount: accountPayRule.canUseDiscount || true,
        requirePassword: accountPayRule.canSkipPwd ? payFee > accountPayRule.skipPwdAmount : true
      }
      // }
      // wx.showModal({
      //   content:"3"+JSON.stringify(account)
      // })
      this.$pay.openPay({
        usableBalance: usableBalance,
        payChannels: payChannels,
        account: account,
        payFee: payFee,
        hasDiscount: hasDiscount,
        confirm: (payChannel, password) => {
          if (payChannel === 'wx') {
            this.startWxPay(orderNo)
            console.log('进入其他方式-微信')
          } else {
            this.startBalancePay(orderNo, password)
            console.log('进入其他方式-余额')
          }
        },
        cancel: () => {
          // 用户取消支付, 跳转到订单详情页
          this._payFail({ code: "cancel", msg: "用户取消支付" });
        }
      })
    },
    startWxPay(orderNo) {
      wxPrepay({ orderNo }).then(res => {
        console.log('商城订单支付--', res)
        this.$pay.hideLoading();
        if (res.code !== 0) {
          this._payFail({ code: res.code, msg: res.msg })
          return;
        }
        wx.requestPayment({
          'timeStamp': res.data.payTimestamp + '',
          'nonceStr': res.data.payNonceStr,
          'package': res.data.payPackage,
          'signType': res.data.paySignType,
          'paySign': res.data.paySignature,
          success: () => {
            this.$pay.showLoading({
              mask: true
            });
            this.startPollOrderStatus(orderNo);
          },
          fail: () => {
            // 用户取消支付, 允许用户重新发起支付
            if (this.$pay.data.visible) {
              this.$pay.hideLoading();
              wx.showToast({ title: "用户取消支付", icon: "none", duration: 1500 })
            } else {
              this._payFail({ code: "cancel", msg: "用户取消支付" });
            }
          }
        })
      }).catch(error => {
        console.error("获取微信支付配置失败", error)
        this._payFail({ code: 500, msg: "获取微信支付配置失败" })
      })
    },
    startBalancePay(orderNo, password,paymentMethod) {
      // noinspection DuplicatedCode
      if (password) {
        password = password//md5(password) 注释md5
      }
      balancePay({ orderNo, password,paymentMethod }).then(res => {
        if (res.code === 0) {
          this.startPollOrderStatus(orderNo);
        } else {
          if (res.code === 50601) {
            // 需要输入密码
            let accountPayRule = this.data.accountPayRule;
            if (accountPayRule && accountPayRule.canSkipPwd) {
              accountPayRule.canSkipPwd = false;
              this.setData({ accountPayRule: accountPayRule })
            }
          } else {
            // 刷新余额
            this.getAccountInfo();
          }
          // 隐藏支付loading, 允许用户重新发起支付
          this.$pay.resetPassword();
          this.$pay.hideLoading();
          setTimeout(function () {
            wx.showToast({ title: res.msg, icon: "none", duration: 4000 })
          }, 500)
        }
      }).catch((error) => {
        console.error("获取会员支付配置失败", error)
        this._payFail({ code: 500, msg: "获取会员支付配置失败" });
      })
    },
    startPollOrderStatus(orderNo) {
      this.setData({ queryTimes: 1 });
      this.innerQuery(orderNo);
    },
    innerQuery(orderNo) {
      if (this.data.queryTimes > 20) {
        this._payFail({ code: "cancel", msg: "查询支付状态超时" });
        return;
      }
      queryOrderStatus({ orderNo }).then(res => {
        if (res.code !== 0) {
          this.setData({ queryTimes: this.data.queryTimes + 1 });
          this.innerQuery(orderNo);
          return;
        }
        let payStatus = res.data;
        if (payStatus === "PAYED" || payStatus === "UNDERWAY" || payStatus === "FINISH") {
          this._paySuccess();
        } else if (payStatus === "WAITING") {
          this.setData({ queryTimes: this.data.queryTimes + 1 });
          this.innerQueryOrderStatus(orderNo);
        } else if (payStatus === "CANCEL") {
          this._payFail({ code: -2, msg: "支付失败,请重试" });
        }
      }).catch(error => {
        this.setData({ queryTimes: this.data.queryTimes + 1 });
        this.innerQuery(orderNo);
        return;
      })
    },
    _paySuccess() {
      this.$pay.hideLoading();
      this.$pay.close();
      this.data.payResolve();
    },
    _payFail(options) {
      let { code, msg } = options
      this.$pay.hideLoading();
      this.$pay.close();
      this.data.payReject({ code, msg })
    }
  }
})
